from rctk.widgets import Window, StaticText, Text, Password, Button
from rctk.layouts import GridLayout

class LoginException(Exception):
    msg = "Login incorrect"

    def __init__(self, msg=None):
        self.msg = msg or self.msg

class UsernameIncorrect(LoginException):
    msg = "User unknown"

class PasswordIncorrect(LoginException):
    msg = "Password incorrect"

class LoginDialog(Window):
    def __init__(self, tk, title="Login"):
        super(LoginDialog, self).__init__(tk, title=title, modal=True)
        self.setLayout(GridLayout(columns=2))
        
        self.alert = StaticText(self.tk, "", height=40, foreground="#ff0000")
        self.append(self.alert, colspan=2)

        self.append(StaticText(self.tk, "Username"))
        self.username = Text(self.tk)
        self.append(self.username)

        self.append(StaticText(self.tk, "Password"))
        self.password = Password(self.tk)
        self.append(self.password)

        self.append(StaticText(self.tk, ""))
        login = Button(self.tk, "Login")
        self.append(login)

        login.click = self.login
        self.layout()

        def default_verify(username, password):
            raise LoginException()
        self.verify_login = default_verify

    def login(self, event):
        username = self.username.value.strip()
        password = self.password.value.strip()

        if not (username and password):
            self.alert.text = "Please provide username and password"
            return
        
        try:
            self.verify_login(username, password)
        except UsernameIncorrect, e:
            self.alert.text = "Username unknown"
        except PasswordIncorrect, e:
            self.alert.text = "Password incorrect"
        except LoginException, e:
            self.alert.text = e.msg
